package com.pavlinic.mylisp.parser;

import java.util.ArrayList;
import java.util.List;

public class Tokenizer {

	private static final char RIGHT_BRACKET = ')';
	private static final char LEFT_BRACKET = '(';
	private static final char DOUBLE_QUOTE = '"';
	private static final char QUOTE = '\'';

	public List<String> getTokens(String string) {
		final List<String> returnedList = new ArrayList<String>();
		final StringBuilder currentToken = new StringBuilder();
		boolean inQuote = false;

		for (int i = 0; i < string.length(); i++) {
			final char currentCharacter = string.charAt(i);
			if (currentCharacter == DOUBLE_QUOTE) {
				if (!inQuote) {
					inQuote = true;
				} else {
					inQuote = false;
					currentToken.append(currentCharacter);
					produceSymbolToken(returnedList, currentToken);
					continue;
				}
			}
			if (inQuote) {
				currentToken.append(currentCharacter);
			} else {
				if (Character.isWhitespace(currentCharacter)) {
					produceSymbolToken(returnedList, currentToken);
				} else if (currentCharacter == LEFT_BRACKET || currentCharacter == RIGHT_BRACKET) {
					produceSymbolToken(returnedList, currentToken);
					returnedList.add(String.valueOf(currentCharacter));
				} else if (currentCharacter == QUOTE) {
					produceSymbolToken(returnedList, currentToken);
					returnedList.add(String.valueOf(currentCharacter));
				} else {
					currentToken.append(currentCharacter);
				}
			}
		}
		produceSymbolToken(returnedList, currentToken);
		return returnedList;
	}

	private void produceSymbolToken(final List<String> returnedList, final StringBuilder currentToken) {
		if (currentToken.length() > 0) {
			returnedList.add(currentToken.toString());
			currentToken.setLength(0);
		}
	}
}
